package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bo.vo.L;
import com.ys.dto.AddDto;
import com.ys.entity.storage.TccLogisticsServiceProviderItem;
import com.ys.entity.storage.TccLogisticsServiceProvider;
import com.ys.entity.storage.TccPreAllocatePublishItem;
import com.ys.entity.storage.TccWarehouse;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.storage.StorageMapper;
import com.ys.mapper.storage.TccAdditionalBillingMapper;
import com.ys.mapper.storage.TccLogisticsServiceProviderItemMapper;
import com.ys.mapper.storage.TccLogisticsServiceProviderMapper;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.TccLogisticsServiceProviderService;
import com.ys.util.AESUtil;
import com.ys.util.CheckUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-05
 * @Description: 物流服务商
 * @Version: 1.5
 */
@Service("tccLogisticsServiceProviderService")
public class TccLogisticsServiceProviderServiceImpl implements TccLogisticsServiceProviderService {
    private static final Logger logger = LoggerFactory.getLogger(TccLogisticsServiceProviderServiceImpl.class);
    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private  TccLogisticsServiceProviderMapper tccLogisticsServiceProviderMapper;

    @Autowired
    private TccLogisticsServiceProviderItemMapper tccLogisticsServiceProviderItemMapper;

    @Autowired
    private TccAdditionalBillingMapper tccAdditionalBillingMapper;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HrMapper hrMapper;

    @Autowired
    private YspTaskService yspTaskService;

    /**
     * 新增
     */
    @Override
    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, Long menuId) throws Exception {
        logger.info("新增传参:" + params);
        //参数验证
        String errorBack = checkParams(params, menuId);
        if (errorBack != null && !"".equals(errorBack)) {
            return R.error(errorBack);
        }
        TccLogisticsServiceProvider tccLogisticsServiceProvider = JSON.parseObject(JSON.toJSONString(params), TccLogisticsServiceProvider.class);
       
        String m="^[A-Za-z0-9]*$";
        if (!tccLogisticsServiceProvider.getTaxNumber().matches(m)){
            return R.error("只能填字符和数字");
        }
        String s="^[0-9]*$";
        if (!tccLogisticsServiceProvider.getPhoneNumber().matches(s)){
            return R.error("只能填数字");
        }

        tccLogisticsServiceProvider.setStatus(1);
        // 加密保存
        tccLogisticsServiceProvider.setFactno(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getFactno()))
                .setSupno(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getSupno()))
                .setSuppass(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getSuppass()))
                .setAppkey(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getAppkey()));
        //新增
        tccLogisticsServiceProviderMapper.insert(tccLogisticsServiceProvider);

        List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
        String errMsgBySub = "";

        if(params.get("subData")!=null){
            JSONArray subData = JSON.parseArray(params.get("subData").toString());
            for (int i = 0; i < subData.size(); i++) {
                JSONObject jSONObject = subData.getJSONObject(i);
                Map<String, Object> paramsNew = new HashMap<>();
                for (String key : jSONObject.keySet()) {
                    paramsNew.put(key,jSONObject.get(key));
                }
                paramsNew.put("pid",tccLogisticsServiceProvider.getId());//单号
                paramsNewByItem.add(paramsNew);
            }
        }else {
            return R.error("详情信息为空！");
        }



        if (errMsgBySub != null && !"".equals(errMsgBySub)){
            return R.error(errMsgBySub);
        }
        hrMapper.deleteTccLogisticsServiceProviderItemById(tccLogisticsServiceProvider.getId());
        for(Map<String, Object> item:paramsNewByItem){
            TccLogisticsServiceProviderItem tccLogisticsServiceProviderItem = JSON.parseObject(JSON.toJSONString(item), TccLogisticsServiceProviderItem.class);
            tccLogisticsServiceProviderItem.setStatus(1);
            tccLogisticsServiceProviderItem.setPid(tccLogisticsServiceProvider.getId());
            if (!tccLogisticsServiceProviderItem.getContactNumber().matches(s)){
                return R.error("只能填数字");
            }
            if (!tccLogisticsServiceProviderItem.getAccountNumber().matches(s)){
                return R.error("只能填数字");
            }
            tccLogisticsServiceProviderItemMapper.insert(tccLogisticsServiceProviderItem);
        }
        return R.ok(AddDto.gotoEdit("/web/storage/tccLogisticsServiceProvider/toEdit?id=" + tccLogisticsServiceProvider.getId()));
    }

    /**
     * 保存
     */
    @Override
    public R save(Map<String, Object> params, Long menuId,Long id) throws Exception {

        TccLogisticsServiceProvider tccLogisticsServiceProvider = JSON.parseObject(JSON.toJSONString(params), TccLogisticsServiceProvider.class);
        // 加密保存
        tccLogisticsServiceProvider.setFactno(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getFactno()))
                .setSupno(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getSupno()))
                .setSuppass(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getSuppass()))
                .setAppkey(AESUtil.aesEncrypt(tccLogisticsServiceProvider.getAppkey()));
        tccLogisticsServiceProviderMapper.update(tccLogisticsServiceProvider);

        //验证详情信息
        List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
        String errMsgBySub = "";

        if(params.get("subData")!=null){
            JSONArray subData = JSON.parseArray(params.get("subData").toString());
            for (int i = 0; i < subData.size(); i++) {
                JSONObject jSONObject = subData.getJSONObject(i);
                Map<String, Object> paramsNew = new HashMap<>();
                for (String key : jSONObject.keySet()) {
                    paramsNew.put(key,jSONObject.get(key));
                }
                paramsNew.put("pid",tccLogisticsServiceProvider.getId());//单号
                paramsNewByItem.add(paramsNew);
            }
        }else {
            return R.error("详情信息为空！");
        }



        if (errMsgBySub != null && !"".equals(errMsgBySub)){
            return R.error(errMsgBySub);
        }
        hrMapper.deleteTccLogisticsServiceProviderItemById(id);
        for(Map<String, Object> item:paramsNewByItem){
            TccLogisticsServiceProviderItem tccLogisticsServiceProviderItem = JSON.parseObject(JSON.toJSONString(item), TccLogisticsServiceProviderItem.class);

            tccLogisticsServiceProviderItem.setStatus(1);
            tccLogisticsServiceProviderItem.setPid(id);
            String s="^[0-9]*$";
            if (!tccLogisticsServiceProviderItem.getContactNumber().toString().matches(s)){
                return R.error("只能填数字");
            }
            if (!tccLogisticsServiceProviderItem.getAccountNumber().toString().matches(s)){
                return R.error("只能填数字");
            }
            tccLogisticsServiceProviderItemMapper.insert(tccLogisticsServiceProviderItem);

        }
        return R.ok(AddDto.gotoEdit("/web/storage/tccLogisticsServiceProvider/toEdit?id=" + tccLogisticsServiceProvider.getId()));
        //return R.ok();
    }



    /**
     * 参数验证
     */
    public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
        //获取pc字段数据
        List<YsCol> listField = new YsCol()
                .where("A.MenuId = " + menuId)
                .setOrderby("A.SortNo ASC")
                .queryList();
        //验证必填字段的非空；其他字段的长度限制、类型
        String backMsg = checkUtil.checkTableColLengthAndDataType("TCC_LogisticsServiceProvider", listField, params, ysColItem -> ysColItem.getFormEditRequired() != null && ysColItem.getFormEditRequired() == 1);
        return backMsg;
    }


    //根据主表bid获取子表信息
    @Override
    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    public List<Map<String, Object>> getItemListById(Long id) throws Exception {
        //获取子表信息
        List<Map<String, Object>> itemList = new TccPreAllocatePublishItem()
                .queryMap();
        return itemList;
    }

    @Override
    public R editDetailBatch(Long LogisticsServiceProviderId, String detailArr) {

        if (LogisticsServiceProviderId == null) {
            return R.error("提交的参数有误，请联系客服");
        }
        TccLogisticsServiceProvider tccLogisticsServiceProvider = new TccLogisticsServiceProvider().setId(LogisticsServiceProviderId).queryFirst();

        JSONArray detailJA = JSON.parseArray(detailArr);

        // 验证数据是否已存在
        List<String> listUnicode = new ArrayList<String>();
        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            String startheavy = detailJO.getString("startheavy");
            String heavyFee = detailJO.getString("heavyFee");
            // 添加调货信息
            BigDecimal originPriceMin = BigDecimal.ZERO;
            BigDecimal originPriceMax = BigDecimal.ZERO;
            return R.ok();
        }
        return null;
    }

    //获取列表数据
    @Override
    @Transactional
    public Map<String,Object> getExtraParam(Long id) throws Exception{
        Map<String, Object> entity = new TccLogisticsServiceProvider().setId(id)
                .queryFirstMap();
        entity.put("status", 1);

        return entity;
    }



    //删除
    @Override
    public int del(long id) throws Exception{
        tccLogisticsServiceProviderMapper.deleteTrue(id);
        return 1;
    }


    @Override
    @Transactional
    public R toDelByItem(Long id) throws Exception {

        TccLogisticsServiceProviderItem tccLogisticsServiceProviderItem = new TccLogisticsServiceProviderItem();
        tccLogisticsServiceProviderItem.setId(id);
        tccLogisticsServiceProviderItem.setStatus(0);
        tccLogisticsServiceProviderItemMapper.update(tccLogisticsServiceProviderItem);
        return R.ok();
    }

    //获取子列表数据
    @Override
    @Transactional
    public List<Map<String, Object>> getItemList(Long id) throws Exception{
        List<Map<String, Object>> itemList = new TccLogisticsServiceProviderItem()
                .addLeftJoin("TCC_LogisticsServiceProvider B ON B.Id=A.Pid")
//                .addField("A.remark premark")
                .setPid(id)
                .queryMap();
        return itemList;
    }

   
}
